import json
import os
import tempfile

from lib.config import flag
import lib.util

"""
文件格式
[文件格式标识(len:2)] +
[文件数量(len:2)] +
[ 
    [数据1长度(len:8)] 
    [数据1标识(len:2)] 
]  + 
[ 
    [数据2长度(len:8)] 
    [数据2标识(len:2)] 
] +
...
[ 
    [数据n长度(len:8)] 
    [数据n标识(len:2)] 
] +
[文件数据1(len:x)] +
[文件数据2(len:x)] +
....
[文件数据n(len:x)] +
[文件格式标识(2)]
"""


class Encode:
    filePath = []
    outputFileName = "out.dp"
    password = None

    def __init__(self, file_path, output_file_name="out.dp", password=None):
        self.filePath = file_path
        if output_file_name is not None:
            self.outputFileName = output_file_name
        ext = lib.util.get_file_ext(self.outputFileName)
        if ext != ".dp":
            self.outputFileName = output_file_name + ".dp"
        if password is not None:
            self.password = password

        self.encode()

    # 文件解析
    def parse_file_data(self):
        header = b""
        temp_file_data = b""
        file_message = {}
        for (index, filePath) in enumerate(self.filePath):
            with open(filePath, "rb") as fs:
                data = fs.read()
                # 64位长度 + 16位文件标识
                header = header + lib.util.data_len_to_bytes(data) + lib.util.num_to_bytes(index)
                temp_file_data = temp_file_data + data
                file_message[str(index)] = lib.util.get_file_msg(filePath)

        return header, temp_file_data, file_message

    def encode(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_dir_path = temp_dir
            header, temp_file_data, file_message = self.parse_file_data()
            num = lib.util.num_to_bytes(len(self.filePath))
            write_temp_file_data = flag + num + header + temp_file_data + flag
            # 写入临时文件
            with open(os.path.join(temp_dir_path, "dp.temp"), "wb") as f:
                f.write(write_temp_file_data)

            with open(os.path.join(temp_dir_path, "data.temp"), 'w') as json_file:
                json.dump(file_message, json_file)

            temp_files = ["dp.temp", "data.temp"]

            # 写入输出文件
            lib.util.save_zip_file(temp_dir_path, temp_files, os.path.join(os.getcwd(), self.outputFileName), self.password)

            print(f"success: output file is [{os.path.join(os.getcwd(), self.outputFileName)}]")
            if self.password is not None:
                print(f"password is [ {self.password} ]. Please keep the secret key properly!")

